package com.csj.mvvm.utils;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import androidx.core.content.FileProvider;

import com.csj.mvvm.App;

import java.io.File;
import java.io.OutputStream;
import java.lang.ref.WeakReference;

// ALPHA_8      表示8位Alpha位图，即A=8,一个像素点占用1个字节,它没有颜色,只有透明度
// ARGB_4444    表示16位ARGB位图，即A=4,R=4,G=4,B=4,一个像素点占4+4+4+4=16位，2个字节
// ARGB_8888    表示32位ARGB位图，即A=8,R=8,G=8,B=8,一个像素点占8+8+8+8=32位，4个字节
// RGB_565      表示16位RGB位图，即R=5,G=6,B=5,它没有透明度,一个像素点占5+6+5=16位，2个字节
public class SDCardUtils {
    private static SDCardUtils instance;
    private WeakReference<OnSaveCallback> callbackWeakReference;

    public static SDCardUtils getDefault() {
        if (instance == null) {
            instance = new SDCardUtils();
        }
        return instance;
    }

    public String SDCardRoot = Environment.getExternalStorageDirectory().getAbsolutePath()
            + File.separator;

    public String getAppDir() {
        ///storage/emulated/0/Android/data/<包名>/files
        String fileUrl = App.instance.getExternalFilesDir(Environment.DIRECTORY_PICTURES) + File.separator;
//        String fileUrl = SDCardRoot + Utils.getApp().getPackageName() + File.separator;
        File file = new File(fileUrl);
        if (!file.exists()) {
            file.mkdir();  //如果不存在则创建
        }
        return fileUrl;
    }

    /**
     * 获得图片保存路径
     */
    public String getPictureDir() {
        String imageCacheUrl = getAppDir() + "images" + File.separator;
        File file = new File(imageCacheUrl);
        if (!file.exists()) {
            file.mkdir();  //如果不存在则创建
        }
        return imageCacheUrl;
    }

    /**
     * 生成新的图片 Uri
     *
     * @return
     */
    public Uri createNewImageUri() {
        String path = getPictureDir() + System.currentTimeMillis() + ".jpg";
        File imgFile = new File(path);
        Uri imageUri = Uri.fromFile(imgFile);

        return imageUri;
    }

    /**
     * 图片保存到SD卡，刷新图库
     */
    public void saveToSdCard(Bitmap bitmap, String fileName, OnSaveCallback callback) {
        callbackWeakReference = new WeakReference<>(callback);
        //        String imagePath = getPictureDir() + System.currentTimeMillis() + ".jpg";
        if (bitmap == null) {
            if (callbackWeakReference.get() != null) callbackWeakReference.get().failure();
        }
        try {
            String imagePath = getPictureDir() + fileName + ".jpg";
            ContentValues values = new ContentValues();
            values.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName);
            values.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg");
            if (Build.VERSION.SDK_INT >= 29) {
                values.put("relative_path", Environment.DIRECTORY_DCIM);
            } else {
                values.put(MediaStore.MediaColumns.DATA, imagePath);
            }
            ContentResolver contentResolver = App.instance.getContentResolver();
            Uri uri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            if (uri != null) {
                OutputStream outputStream = contentResolver.openOutputStream(uri);
                if (outputStream != null) {
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                    outputStream.flush();
                    outputStream.close();
                    //保存图片后发送广播通知更新数据库
                    File file = new File(imagePath);
                    Uri uri1;
                    if (Build.VERSION.SDK_INT >= 24) {
                        uri1 = FileProvider.getUriForFile(App.instance, App.instance.getPackageName() + ".FileProvider", file);
                    } else {
                        uri1 = Uri.fromFile(file);
                    }
                    App.instance.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri1));
                }
            }
            if (callbackWeakReference.get() != null)
                callbackWeakReference.get().success(new File(imagePath));
        } catch (Exception e) {
            if (callbackWeakReference.get() != null) callbackWeakReference.get().failure();
        }
    }

    /**
     * 格式化图片为 RGB_565
     *
     * @param imagePath 文件地址
     * @return
     */
    public Bitmap compressByRGB_565(String imagePath) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        Bitmap mBitmap = BitmapFactory.decodeFile(imagePath, options);
        return mBitmap;
    }

    /**
     * 保存图片监听
     */
    public interface OnSaveCallback {
        void success(File file);

        void failure();
    }
}
